import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  // 加载环境变量
  const env = loadEnv(mode, process.cwd(), '')
  
  return {
  plugins: [react()],
  server: {
    port: 3000,
    host: true,
    proxy: {
      '/api': {
        target: env.VITE_API_BASE_URL ? env.VITE_API_BASE_URL.replace('/api', '') : 'http://172.25.6.39:3001',
        changeOrigin: true,
        secure: false,
        rewrite: (path) => path,
        // 添加更多调试选项
        configure: (proxy, options) => {
          proxy.on('proxyReq', (proxyReq, req, res) => {
            console.log(`[VITE] 代理请求: ${req.url} -> ${proxyReq.path}`);
          });
          proxy.on('error', (err, req, res) => {
            console.error(`[VITE] 代理错误: ${err.message}`);
          });
          proxy.on('proxyRes', (proxyRes, req, res) => {
            console.log(`[VITE] 代理响应: ${req.url} 状态码: ${proxyRes.statusCode}`);
          });
        }
      }
    }
  },
  build: {
    rollupOptions: {
      output: {
        // 手动分割代码块，将大型库单独打包
        manualChunks: {
          // 将React相关库单独打包
          'react-vendor': ['react', 'react-dom', 'react-router-dom'],
          // 将Ant Design基础组件单独打包
          'antd-core': ['antd/es/layout', 'antd/es/menu', 'antd/es/dropdown', 'antd/es/avatar', 'antd/es/button', 'antd/es/space', 'antd/es/typography', 'antd/es/card', 'antd/es/statistic', 'antd/es/row', 'antd/es/col', 'antd/es/spin', 'antd/es/alert', 'antd/es/tooltip'],
          // 将Ant Design图标单独打包
          'antd-icons': ['@ant-design/icons'],
          // 将Ant Design图表库单独打包
          'antd-plots': ['@ant-design/plots'],
          // 将其他第三方库单独打包
          'other-vendor': ['lucide-react']
        }
      }
    },
    // 进一步优化代码分割解决Chunk大小问题
    // 从最新的构建输出可以看到，我们的代码分割配置已经生效了，将原本1.7MB的antd-vendor拆分成了几个更小的块：
    // - `antd-core`: 476.84 kB
    // - `antd-plots`: 1,243.09 kB
    // - `antd-icons`: 31.32 kB
    // - `react-vendor`: 44.98 kB
    
    //虽然大多数块都在1000kB以下，但`antd-plots`仍然超过了阈值。让我们进一步优化：
    // 调整chunk大小警告阈值
    chunkSizeWarningLimit: 1500 // 单位为kB，将阈值从1000调整到1500
  }
  }
})
